package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/hashicorp/go-version"
	"github.com/jmoiron/sqlx"
	"vip_video/internal/library"
)

func CheckAppMiddleware(db *sqlx.DB) gin.HandlerFunc {
	return func(context *gin.Context) {
		//获取 header 里面的 token
		response := library.NewResponse(context)
		appVersion := context.GetHeader("X-Version")
		platform := context.GetHeader("X-Platform")
		if appVersion == "" || platform == "" {
			response.ErrorAbort("禁止访问!")
			return
		}
		c := library.NewSystemConfigLibrary(db)
		v, err := c.Get("app_version")
		if err != nil {
			response.ErrorAbort("系统错误,请联系管理员[0]!")
			return
		}
		v1, err := version.NewVersion(appVersion)
		if err != nil {
			response.ErrorAbort("系统错误,请联系管理员[1]!")
			return
		}
		v2, err := version.NewVersion(*v.Value)
		if err != nil {
			response.ErrorAbort("系统错误,请联系管理员[2]!")
			return
		}
		if v1.LessThan(v2) {
			response.ErrorAbort("app版本较低,请下载最先版本的app!")
			return
		}
		context.Next()
	}
}
